//添加广告
import { useNavigate } from "react-router-dom";
import { PlusOutlined, LoadingOutlined } from "@ant-design/icons";
import { useEffect } from "react";
import axios from "../../utils/myAixos";
import { useLocation} from 'react-router-dom'
import {
  Button,
  // Checkbox,
  Form,
  Input,
  Select,
  DatePicker,
  Radio,
  Upload,
  message,
  //   TextArea,
} from "antd";
import { useState } from "react";
//和上传有关的方法

const getBase64 = (img, callback) => {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result));
  reader.readAsDataURL(img);
};
const { RangePicker } = DatePicker;
const { TextArea } = Input;
const { Option } = Select;
//添加广告数据的函数

const onFinishFailed = (errorInfo) => {
  console.log("Failed:", errorInfo);
};

const ChangeGg = () => {
  //页面初始获取数据

  const  location = useLocation();
  const [changeDate,setChangeDate]=useState([])
  //修改数据的ID
  const [dataId,setDateId]=useState()
//   const [title,setTiTle]=useState()
  useEffect(() => {

    console.log(location.state)
    setDateId(location.state.id)
    // setTiTle(location.state.title)
    // console.log(dataId)
    //  console.log(title)
  });
  const navigate = useNavigate();
  const [messageApi, contextHolder] = message.useMessage();
  const onFinish = (values) => {
    console.log("Success:", values);
    let myFormData = new FormData();
    //第二步，讲文件装到这个盒子里面去  组装数据
    // myFormData.append(内容的名字，内容)  如果这个内容是一个文件，放的就是文件对象
    console.log(values.time[0]);
    const date = new Date(values.time[0]);
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    let newDate = year + "-" + month + "-" + day;
    // console.log(newDate)
    myFormData.append("myFile", values.myfile.file.originFileObj);
    myFormData.append("title", values.name);
    myFormData.append("position", values.position);
    myFormData.append("startTime", newDate);
    myFormData.append("class", values.class);
    myFormData.append("id",dataId)
    axios({
      url: "/adEdit",
      method: "post",
      data: myFormData,
    })
      .then((res) => {
        console.log(res);
        if (res.status === 200) {
          console.log(11111);
          messageApi.info("修改成功!");
          setTimeout(() => {
            navigate(-1);
          }, 500);
        } else {
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };

  const [dates, setDates] = useState(null);
  const [value, setValue] = useState(null);
  const disabledDate = (current) => {
    if (!dates) {
      return false;
    }
    const tooLate = dates[0] && current.diff(dates[0], "days") >= 7;
    const tooEarly = dates[1] && dates[1].diff(current, "days") >= 7;
    return !!tooEarly || !!tooLate;
  };
  const onOpenChange = (open) => {
    if (open) {
      setDates([null, null]);
    } else {
      setDates(null);
    }
  };

  const getBack = () => {
    navigate(-1);
  };
  //和上传图片有关
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState("");
  const handleChange = (info) => {
    console.log("%c ======>>>>>>>>", "color:orange;", "info", info);
    //判断他的类型和大小
    const isJpgOrPng =
      info.file.type === "image/jpeg" ||
      info.file.type === "image/png" ||
      info.file.type === "image/jpg";
    if (!isJpgOrPng) {
      return message.error("只能上传 jpeg/jpg/png 图片");
    }
    const isLt2M = info.file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      return message.error("最大只能上传2M的图片");
    }
    //将文件对象转成base64的地址，img才能显示出来
    getBase64(info.file.originFileObj, (url) => {
      // console.log(url);
      setImageUrl(url);
    });
  };
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div
        style={{
          marginTop: 8,
        }}
      >
        Upload
      </div>
    </div>
  );
  const customRequest = () => {
    console.log("customRequest 执行了");
  };

  return (
    <div
      style={{
        width: "100%",
        display: "flex",
        flexDirection: "column",
        alignItems: "center",
        height: "98%",
        borderRadius: "8px 8px 0px 0px",
      }}
    >
      <div
        style={{
          overflowY: "scroll",
          width: "97%",
          display: "flex",
          alignItems: "center",
          flexDirection: "column",
          marginTop: "10px",
          height: "100%",
          borderRadius: "8px 8px 0px 0px",
          border: "1px solid #e4e4e4",
        }}
      >
        <div
          style={{
            width: "100%",
            display: "flex",
            justifyContent: "flex-start",
            zIndex: "999",
            height: "8%",
            backgroundColor: "#f3f3f3",
          }}
        >
          <div
            style={{
              display: "flex",
              justifyContent: "space-between",
              width: "100%",
              alignItems: "center",
              fontSize: "14px",
            }}
          >
            <div style={{ marginLeft: "2%" }}>修改广告</div>
            <div style={{ marginRight: "2%" }}>
              <button
                onClick={getBack}
                style={{
                  width: "60px",
                  height: "30px",
                  borderRadius: "4px 4px 4px 4px",
                  backgroundColor: "white",
                  color: "#767676",
                  border: "0px",
                }}
              >
                返回
              </button>
            </div>
          </div>
        </div>
        <div style={{ marginTop: "2%" }}>
          <Form
            name="basic"
            labelCol={{
              span: 8,
            }}
            wrapperCol={{
              span: 16,
            }}
            style={{
              maxWidth: 600,
            }}
            initialValues={{
              remember: true,
            }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            autoComplete="off"
          >
            <Form.Item
              label="广告名称"
              name="name"
              rules={[
                {
                  required: true,
                  message: "请输入广告名称!",
                },
              ]}
            >
              <Input placeholder="输入广告名称" />
            </Form.Item>

            <Form.Item
              name="position"
              label="广告位置"
              rules={[
                {
                  required: true,
                  message: "请选择轮播位置",
                },
              ]}
            >
              <Select
                style={{ textAlign: "left" }}
                placeholder="选择轮播位置"
                //   onChange={onGenderChange}
                allowClear
              >
                <Option value="首页轮播">首页轮播</Option>
                <Option value="商城首页轮播">商城首页轮播</Option>
              </Select>
            </Form.Item>
            <Form.Item
              label="请选择日期"
              name="time"
              style={{ marginTop: "10px" }}
              rules={[{ required: true, message: "时间必选" }]}
            >
              {/* <span style={{ marginLeft: "70px", marginRight: "10px" }}>
              请选择日期
            </span> */}
              <RangePicker
                value={dates || value}
                disabledDate={disabledDate}
                onCalendarChange={(val) => setDates(val)}
                onChange={(val) => setValue(val)}
                onOpenChange={onOpenChange}
              />
            </Form.Item>
            <Form.Item
              label="上线/下线"
              name="class"
              style={{ marginTop: "10px" }}
              rules={[{ required: true, message: "方式必须" }]}
            >
              <Radio.Group style={{ width: "300px" }}>
                <Radio value="上线" style={{ marginLeft: "-160px" }}>
                  {" "}
                  上线{" "}
                </Radio>
                <Radio value="下线"> 下线 </Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item
              label="广告图片"
              name="myfile"
              rules={[{ required: true, message: "头像必选" }]}
            >
              <Upload
                name="avatar"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                onChange={handleChange}
                customRequest={customRequest}
              >
                {imageUrl ? (
                  <img
                    src={imageUrl}
                    alt="该图片有问题"
                    style={{
                      width: "100%",
                      height: "100%",
                      // border:"1px solid red"
                    }}
                  />
                ) : (
                  uploadButton
                )}
              </Upload>
            </Form.Item>
            <Form.Item label="广告备注" name="广告备注">
              <TextArea rows={4} />
            </Form.Item>
            <Form.Item
              wrapperCol={{
                offset: 2,
                span: 16,
              }}
            >
              <Button
                type="primary"
                htmlType="submit"
                style={{ backgroundColor: "#00ccff" }}
              >
                保存
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
      {contextHolder}
    </div>
  );
};
export default ChangeGg;
